/**
 * My simple header template from child directory
 * IPv4.java - ${projectName} - ${organizationName} - ${inceptionYear}
 */
/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 02.11.13
 * Time: 16:00
 * To change this template use File | Settings | File Templates.
 */
public class IPv4 {

    private String address;
    private int binaryRepresentation;
    private static final String IP_PATTERN = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                             "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                             "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                             "([01]?\\d\\d?|2[0-4]\\d|25[0-5])" +
                                             "/([0-2]?\\d|3[0-2])";

    public IPv4(String address) {
        this.address = address;
        if (isCorrect()) {
            this.binaryRepresentation = toBinaryRepresentation();
        }
        else this.binaryRepresentation = 0;
    }

    public boolean isCorrect() {
        return address.matches(IP_PATTERN);
    }

    public int toBinaryRepresentation() {
        int binaryRepresentation = 0, n = 24;
        String[] splitAddress = address.substring(0, address.lastIndexOf('/')).split("\\.");
        for (String range: splitAddress) {
            binaryRepresentation = binaryRepresentation | (Integer.parseInt(range) << n);
            n -= 8;
        }
        return binaryRepresentation;
    }

    public int getSuffix() {
        return Integer.parseInt(address.substring(address.indexOf('/')+1));
    }

    public int getBinaryRepresentation() {
        return binaryRepresentation;
    }
}
